import React from 'react'
import { UdPageHeader, UdFilter, UdDatePicker, http, validators } from '@/lib'
import { Button, Table, Select, message, Alert } from 'antd'
import apis from '@/apis/FundsManage'
import './index.scss'
import dayjs from 'dayjs';
import qs from 'qs'
import { downBlobFile } from '@/utils/methods'
import UdSelect from '@/components/UdFormControls/UdSelect'
import { getBrandSelectList, getDealerListByBrand } from '@/common/Request'
import { WrappedFormUtils } from 'antd/lib/form/Form'
import moment from 'moment'

const fieldMap = {
  //开始时间
  startTime: "startDate",
  //结束时间
  endTime: "endDate",

  //记账日期
  bookkeepingDate: "bookkeepingDate",
  //凭证编号
  documentNo: "documentNo",
  //借方
  debit: "debit",
  //贷方
  lender: "lender",
  //余额
  balance: "balance",
  //备注
  remark: "remark",
}

export default class List extends React.Component {

  private filterForm: WrappedFormUtils

  state = {
    selectedRowKeys: [],
    searchValues: {
      brandCodes: undefined,
      startDate: `${dayjs().format('YYYY')}-01-01 00:00:00`,
      endDate: dayjs().format("YYYY-MM-DD 23:59:59"),
      dealerCode: undefined,
    },
    page: 1,
    size: 10,
    total: 0,
    tableData: [],
    loading: false,
    brandOptions: [],
    dealerCodeOptions: [],
    contactsCount: { // 往来账明细合计数据
      lendMoney: 0, // 借方
      loanMoney: 0, // 贷方
      balance: 0, // 余额
    },
  }

  /* componentWillMount() {
    this.getList()
  } */
  
  componentDidMount() {
    this.getBrandList()
  }

  private getBrandList = () => {
    getBrandSelectList().then(result => {
      this.setState({
        brandOptions: result,
      })
    })
  }

  private getDealerListByBrand = (code) => {
    // 组织切换，重置经销商条件
    this.filterForm.setFieldsValue({ dealerCode: undefined })
    getDealerListByBrand(code).then(result => {
      this.setState({
        dealerCodeOptions: result,
      })
    })
  }

  //更新列表数据
  private getList = async () => {
    this.setState({ loading: true })

    let brandCodes = this.state.searchValues?.brandCodes ? [this.state.searchValues?.brandCodes] : undefined
    let startDate = this.state.searchValues?.startDate && moment(this.state.searchValues?.startDate).format('YYYY-MM-DD 00:00:00')
    let endDate = this.state.searchValues?.endDate && moment(this.state.searchValues?.endDate).format('YYYY-MM-DD 23:59:59')
    try {
      let list: any = await http.post(apis.getMarginList, {
        page: this.state.page,
        size: this.state.size,
        ...this.state.searchValues,
        startDate,
        endDate,
        brandCodes,
      },
        {
          paramsSerializer: function (params) {
            return qs.stringify(params, { arrayFormat: 'repeat' })
          }
        })

      let allList: any = await http.post(apis.getMarginAcount, {
        page: this.state.page,
        size: this.state.size,
        dealerCode: this.state.searchValues.dealerCode,
        brandCodes,
        startDate,
        endDate,
      },
        {
          paramsSerializer: function (params) {
            return qs.stringify(params, { arrayFormat: 'repeat' })
          }
        })

      const listcountAll = allList?.data

      const tableData = list.data?.content

      this.setState({
        tableData,
        page: list.data.number,
        size: list.data.size,
        total: list.data.totalElements,
        loading: false,
        contactsCount: {
          lendMoney: listcountAll?.sumLendMoney || 0,
          loanMoney: listcountAll?.sumLoanMoney || 0,
          balance: listcountAll?.sumBalance || 0,
        },
      })
    } catch (error) {
      this.setState({
        loading: false,
      })
    }
  }

  //分页,修改每页显示条数
  private handleChangePage = (pagination) => {
    const { current: page, pageSize: size } = pagination
    this.setState({ page, size }, () => {
      // this.getList()
    })
  }


  //搜索
  private handleSearch = (values) => {

    this.setState({ searchValues: values, page: 1 }, () => {
      this.getList()
    })
  }

  //导出
  private hendleExport = () => {

    const { brandCodes: brandCode, dealerCode } = this.state.searchValues
    if (!brandCode || !dealerCode) {
      message.error('请选择销售组织和经销商查询后操作')
      return
    }

    let brandCodes = this.state.searchValues?.brandCodes ? [this.state.searchValues?.brandCodes] : undefined
    let startDate = this.state.searchValues?.startDate && moment(this.state.searchValues?.startDate).format('YYYY-MM-DD 00:00:00')
    let endDate = this.state.searchValues?.endDate && moment(this.state.searchValues?.endDate).format('YYYY-MM-DD 23:59:59')


    http.post(apis.depositDownload, {
      page: this.state.page,
      size: this.state.size,
      ...this.state.searchValues,
      startDate,
      endDate,
      brandCodes,
    },
      {
        responseType: "arraybuffer",
        paramsSerializer: function (params) {
          return qs.stringify(params, { arrayFormat: 'repeat' })
        }
      },
    ).then(res => {
      if (!res.data.code) {
        downBlobFile(res.data, "保证金单")
      }
    })
  }

  private resetFilterHandle = () => {
    this.setState({
      tableData: [],
      contactsCount: {
        lendMoney: 0,
        loanMoney: 0,
        balance: 0,
      },
      page: 1,
      total: 0,
    })
  }

  render() {
    return <div className="funds-list-box">
      {/* <UdPageHeader title="我的保证金" /> */}
      <UdPageHeader title="我的保证金" subTitle="数据仅供参考，最终以财务提供为准" subTitleColor={'red'} />
      <div className="table-front-btns-box">
        <div className="type-change-box"><span style={{ borderBottom: "2px solid #00c1de", color: "#00c1de" }}>保证金明细</span></div>
      </div>
      <UdFilter
        items={[
          {
            id: "brandCodes",
            label: "销售组织",
            rules: [validators.required],
            render: <UdSelect onChange={this.getDealerListByBrand} allowClear={false} options={this.state.brandOptions} />
          },
          {
            id: "dealerCode",
            label: "经销商",
            rules: [validators.required],
            render: <UdSelect allowClear={false} showSearch={true} options={this.state.dealerCodeOptions} />
          },
          {
            id: fieldMap.startTime,
            label: "开始时间",
            initialValue: moment(`${moment().format('YYYY')}-01-01 00:00:00`),
            render: <UdDatePicker />
          },
          {
            id: fieldMap.endTime,
            label: "结束时间",
            initialValue: moment(moment().format('YYYY-MM-DD 23:59:59')),
            render: <UdDatePicker />
          }
        ]}
        onSearch={(values) => { this.handleSearch(values) }}
        loading={this.state.loading}
        getForm={(form) => this.filterForm = form}
        resetAfter={this.resetFilterHandle}
      />
      <div className="export-btn"><Button onClick={() => {
        this.hendleExport()
      }} type="primary">导出</Button></div>
      <Alert
        className="moneycount-extra-tips"
        message={<div>合计：借方 <span className="num">{this.state.contactsCount.lendMoney}</span>，贷方 <span className="num">{this.state.contactsCount.loanMoney}</span>，余额 <span className="num">{this.state.contactsCount.balance}</span></div>}
      />
      <Table
        className="has-sum-table"
        rowKey={(record, index) => index + ""}
        dataSource={this.state.tableData}
        loading={this.state.loading}
        columns={[
          {
            dataIndex: "brandName",
            title: "销售组织"
          },
          {
            dataIndex: "recordDate",
            title: "记账日期",
            render: (text) => text ? dayjs(text).format("YYYY-MM-DD") : ""
          },
          {
            dataIndex: "lendMoney",
            title: "借方",
            align: 'right',
          },
          {
            dataIndex: "loanMoney",
            title: "贷方",
            align: 'right',
          },
          {
            dataIndex: "balance",
            title: "余额",
            align: 'right',
          },
          {
            dataIndex: "description",
            title: "备注"
          }
        ]}
        onChange={this.handleChangePage}
        pagination={{
          current: this.state.page,
          pageSize: this.state.size,
          total: this.state.total,
          showQuickJumper: true,
          showSizeChanger: true,
          pageSizeOptions: ['10', '20', '30', '40'],
          showTotal: (total, range) => `共${total}项，当前${range[0]}-${range[1]}项`,
        }}
      />
    </div>
  }
}